package com.rgp.serviceprice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rgp.internalcommon.common.CommonStatusEnum;
import com.rgp.internalcommon.dto.ForecastPriceDto;
import com.rgp.internalcommon.dto.ResponseResult;
import com.rgp.internalcommon.response.ForecastPriceResponse;
import com.rgp.serviceprice.utils.TollRulePriceCalculateUtils;
import com.rgp.serviceprice.feign.ServiceMapClient;
import com.rgp.serviceprice.mapper.TollRuleMapper;
import com.rgp.serviceprice.pojo.TollRule;
import com.rgp.serviceprice.service.ForecastPriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author nhp
 * @version 1.0
 * @description TODO
 * @date 2024-04-14 1:41
 */
@Service
public class ForecastPriceServiceImpl implements ForecastPriceService {

    @Autowired
    private ServiceMapClient serviceMapClient;

    @Autowired
    private TollRuleMapper tollRuleMapper;

    @Override
    public ResponseResult forecastPrice(ForecastPriceDto forecastPriceDto) {
        //1.根据起点与终点之间的经纬度，计算两地之间的距离distance与时长duration
        ResponseResult distanceDuration = serviceMapClient.forecastDistanceDuration(forecastPriceDto);
        Map<String,String> data = (Map<String,String>)distanceDuration.getData();
        //行驶距离
        String distance = data.get("distance");
        //行驶时间
        String duration = data.get("duration");

        //2.根据乘客所在城市的cityCode 与 所选载具的类型 vehicleType来查询最新版本的计价规则
        String cityCode = forecastPriceDto.getCityCode();
        Integer vehicleType = forecastPriceDto.getVehicleType();
        String fareType = cityCode + "$" + vehicleType;
        QueryWrapper<TollRule> wrapper = new QueryWrapper<>();
        wrapper.eq("fare_type",fareType);
        wrapper.orderByDesc("fare_version");
        List<TollRule> tollRules = tollRuleMapper.selectList(wrapper);
        //获取当前fareType下的最新版本的计价规则
        if (tollRules == null || tollRules.size() == 0){
            return ResponseResult.fail(CommonStatusEnum.TOLL_RULE_NOT_EXIST);
        }
        TollRule tollRule = tollRules.get(0);

        //3.计算预估价格
        String price = TollRulePriceCalculateUtils.calculatePrice(tollRule, distance, duration);

        //4.返回预估价格
        ForecastPriceResponse response = new ForecastPriceResponse();
        response.setPrice(price);
        response.setFareType(fareType);
        response.setFareVersion(tollRule.getFareVersion());
        return ResponseResult.success(response);
    }
}